package com.by.log.statistic;

import com.by.log.entity.StatisticData;
import com.by.log.handler.StatisticCollector;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 统计信息管理器
 * 用于统一管理所有类的统计信息
 */
public class StatisticManager {
    private static final StatisticManager INSTANCE = new StatisticManager();
    
    // 存储所有统计收集器
    private final Map<String, StatisticCollector> collectors = new ConcurrentHashMap<>();
    
    private StatisticManager() {
    }
    
    public static StatisticManager getInstance() {
        return INSTANCE;
    }
    
    /**
     * 注册统计收集器
     * @param className 类名
     * @param collector 统计收集器
     */
    public void registerCollector(String className, StatisticCollector collector) {
        collectors.put(className, collector);
    }
    
    /**
     * 注册统计收集器
     * @param clazz 类
     * @param collector 统计收集器
     */
    public void registerCollector(Class<?> clazz, StatisticCollector collector) {
        registerCollector(clazz.getName(), collector);
    }
    
    /**
     * 获取统计收集器
     * @param className 类名
     * @return 统计收集器
     */
    public StatisticCollector getCollector(String className) {
        return collectors.get(className);
    }
    
    /**
     * 获取统计收集器
     * @param clazz 类
     * @return 统计收集器
     */
    public StatisticCollector getCollector(Class<?> clazz) {
        return getCollector(clazz.getName());
    }
    
    /**
     * 收集所有统计信息并重置
     * @return 统计信息映射
     */
    public Map<String, StatisticData> collectAllAndReset() {
        Map<String, StatisticData> allStats = new ConcurrentHashMap<>();
        for (Map.Entry<String, StatisticCollector> entry : collectors.entrySet()) {
            try {
                Map<String, StatisticData> stats = entry.getValue().collectAndReset();
                allStats.putAll(stats);
            } catch (Exception e) {
                System.err.println("Error collecting stats for " + entry.getKey() + ": " + e.getMessage());
            }
        }
        return allStats;
    }
    
    /**
     * 获取所有统计收集器
     * @return 统计收集器映射
     */
    public Map<String, StatisticCollector> getAllCollectors() {
        return collectors;
    }
}